package com.cqhz.quwan.ui.base

import android.database.DataSetObserver
import android.view.View
import android.widget.ImageView
import android.widget.ListView
import com.cqhz.quwan.R


abstract class AbsListViewFragment<T> : AbsFragment() {
    private lateinit var listView: ListView
    private lateinit var simpleAdapter: AbsAdapter<T>
    private lateinit var listStubView: ImageView

    private val dataSetObserver = object : DataSetObserver() {
        override fun onChanged() {
            val size = simpleAdapter.mData.size
            if (size == 0) {
                listStubView.visibility = View.VISIBLE
                listView.visibility = View.GONE
            } else {
                listStubView.visibility = View.GONE
                listView.visibility = View.VISIBLE
            }
        }
    }

    override fun layout(): Int {
        return R.layout.fragment_listview
    }

    override fun initView() {
        with(view) {
            listView = this!!.findViewById(R.id.lv_fragment)
            listStubView = this.findViewById(R.id.list_stub)
        }
        simpleAdapter = initAdapter()
        simpleAdapter.registerDataSetObserver(dataSetObserver)
        listView.adapter = simpleAdapter
        initData()
    }

    override fun onDestroy() {
        simpleAdapter.unregisterDataSetObserver(dataSetObserver)
        super.onDestroy()
    }

    abstract fun initAdapter(): AbsAdapter<T>

    abstract fun initData()

    fun adapter(): AbsAdapter<T> {
        return simpleAdapter
    }
}